package com.yhy.admin.action;

import com.yhy.admin.dto.FileUploadDTO;
import com.yhy.admin.service.mng.FtpManageService;
import com.yhy.common.action.BaseAction;
import com.yhy.common.dto.AppReturnMsg;
import com.yhy.common.dto.ReturnCode;
import com.yhy.common.exception.BusinessException;
import com.yhy.common.intercept.LoginPermission;
import com.yhy.common.service.SysAttachmentService;
import com.yhy.common.utils.FileUtils;
import com.yhy.common.utils.YhyUtils;
import com.yhy.common.vo.SysAttachment;
import com.yhy.common.vo.SysUser;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 19-11-20 下午2:34 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2019<br>
 *  *
 *
 */
@RestController
@RequestMapping(value="/admin-service/api/fileMng", produces="application/json;charset=UTF-8")
public class FileMngAction extends BaseAction<FileUploadDTO> {
    @Autowired
    private FtpManageService ftpManageService;

    /*
     * 文件上传 仅上传到 临时文件夹上， 没放到ftp服务器上
     */
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="文件上传", notes="文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attachment", value = "文件域", required = true, dataTypeClass = MultipartFile.class)
    })
    public AppReturnMsg upload(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) {
        //临时文件名
        SysUser sysUser = YhyUtils.getSysUser();
        SysAttachment sysAttachment = new SysAttachment();
        sysAttachment.setCreateBy(sysUser.getUserAccount());
        ftpManageService.upload(sysAttachment, file, false);
        return new AppReturnMsg(ReturnCode.SUCCESS_CODE.getCode(),"文件上传成功",sysAttachment,null);
    }

    /*
     * 文件上传 上传到放到ftp服务器上
     */
    @RequestMapping(value="/directUpload",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="文件直接上传", notes="文件直接上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attachment", value = "文件域", required = true, dataTypeClass = MultipartFile.class)
    })
    public AppReturnMsg directUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) {
        //临时文件名
        SysUser sysUser = YhyUtils.getSysUser();
        SysAttachment sysAttachment = new SysAttachment();
        sysAttachment.setCreateBy(sysUser.getUserAccount());
        ftpManageService.upload(sysAttachment, file, true);
        return new AppReturnMsg(ReturnCode.SUCCESS_CODE.getCode(),"文件上传成功",sysAttachment,null);
    }


    @RequestMapping(value="/displayImage",method = {RequestMethod.GET})
    @ResponseBody
    @LoginPermission(loginRequired=false)
    @ApiOperation(value="图片显示", notes="图片显示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, dataTypeClass =String.class)
    })
    public AppReturnMsg displayImage(@RequestParam(value = "filePath",required = true) String filePath, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            ftpManageService.begin();
            ftpManageService.downloadAttachment(filePath, response.getOutputStream());
        } catch (Exception e) {
            response.setHeader("Content-Disposition", "");
            response.setContentType("text/html;charset=UTF-8");
            throw new BusinessException("下载失败。"+e.getMessage(), e);
        } finally {
            ftpManageService.end();
        }
        return null;
    }

    @RequestMapping(value="/downloadAttachment",method = {RequestMethod.GET})
    @ResponseBody
    @LoginPermission(loginRequired=false)
    @ApiOperation(value="从ftp下载文件", notes="从ftp下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, dataTypeClass =String.class)
    })
    public AppReturnMsg downloadAttachment(@RequestParam(value = "filePath",required = true) String filePath, HttpServletRequest request, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            String fileName = FileUtils.getName(filePath);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859-1") + "\"");
            ftpManageService.begin();
            ftpManageService.downloadAttachment(filePath, outputStream);
        } catch (Exception e) {
            response.setHeader("Content-Disposition", "");
            response.setContentType("text/html;charset=UTF-8");
            throw new BusinessException("下载失败。"+e.getMessage(), e);
        } finally {
            ftpManageService.end();
            IOUtils.closeQuietly(outputStream);
        }
        return null;
    }

    /**
     * 从系统路径下载文件
     */
    @RequestMapping(value="/downloadSysAttachment",method = {RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value="从系统路径下载文件", notes="从系统路径下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, dataTypeClass =String.class)
    })
    public AppReturnMsg downloadSysAttachment(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "filePath",required = true) String filePath) {
        OutputStream outputStream = null;
        InputStream importTemplate = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            String fileName = FileUtils.getName(filePath);
            outputStream = response.getOutputStream();
            importTemplate = YhyUtils.getInputStream(filePath);
            IOUtils.copy(importTemplate, outputStream);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/octet-stream");
            outputStream.flush();
            return null;
        } catch (Exception e) {
            LOGGER.error("下载失败", e);
            String msg = StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "下载失败";
            return new AppReturnMsg(ReturnCode.FAIL_CODE.getCode(), msg);
        } finally {
            IOUtils.closeQuietly(importTemplate);
            IOUtils.closeQuietly(outputStream);
        }
    }

}
